﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Wsq.Utils.DoNetFramework40.Socket.tools;
using Wsq.Utils.DoNetFramework40.Socket;
using System.Configuration;
using Oracle.ManagedDataAccess.Client;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Buffers.Text;

namespace HundSunDBQryServer
{
    internal class MyHttpServer : HttpServer
    {
        Dictionary<int, string> bankMap=new Dictionary<int, string>() 
        {
            { 0,"内部" },
            { 1,"工商银行"},
            { 2,"农业银行"},
            { 3,"建设银行"},
            { 4,"交通银行"},
            { 5,"招商银行"},
            { 6,"中国银行"},
            { 11,"中信银行"},
        };
        Dictionary<int, string> businessMap = new Dictionary<int, string>()
        {
            { 2041 ,"银行转存" },
            { 2042 ,"银行转取"},
        };


        public MyHttpServer(int port, string wsPath = "/") : base(port, wsPath)
        {
        }

        public override void handleRequest(HttpReadParse readParse, HttpResponse response)
        {
            //Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}>> Method:{readParse.HttpRequestMethed} Url:{readParse.HttpRequestUrl}");
            if (readParse.HttpRequestMethed == "GET")
            {
                //Console.WriteLine(readParse.HttpRequestUrl);
                string urlpath = readParse.HttpRequestUrl.Split('?')[0];

                switch (urlpath)
                {
                    case "/QryFundJour":

                        WebRsp rsp = new WebRsp();
                        string sdate = "";
                        string edate = "";
                        foreach (var item in readParse.GetReqParam())
                        {
                            if (item.Key == "sdate")
                            {
                                sdate = item.Value;
                            }
                            else if (item.Key == "edate")
                            {
                                edate = item.Value;
                            }
                        }
                        if (sdate != "" && edate != "")
                        {
                            try
                            {
                                DateTime sdt = DateTime.ParseExact(sdate, "yyyyMMdd", null);
                                DateTime edt = DateTime.ParseExact(edate, "yyyyMMdd", null);
                                // 打开数据库连接
                                var data = HundSunDB.GetFundJours(sdt, edt);
                                rsp.code = 0;
                                foreach (var item in data)
                                {
                                    rsp.data.Add(item);
                                }
                                rsp.errmsg = "正确";
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error connecting to Oracle database: " + ex.StackTrace);
                                rsp.code = -1;
                                rsp.errmsg = ex.Message;
                            }
                        }
                        else
                        {
                            rsp.code = -2;
                            rsp.errmsg = "请输入正确的参数";
                        }
                        response.WriteSuccess();
                        response.Write(JsonConvert.SerializeObject(rsp));
                        break;

                    case "/QrySqlStr":
                        QrySqlStr(readParse, response);
                        break;
                    default:
                        {
                            response.WriteFailure();
                        }
                        break;
                }
            }
            else if (readParse.HttpRequestMethed == "POST")
            {
                //Console.WriteLine(readParse.HttpRequestUrl);
                string urlpath = readParse.HttpRequestUrl.Split('?')[0];
                switch (urlpath)
                {
                    case "/api/UserLogin"://登录
                        UserLogin(readParse, response);
                        break;
                    case "/api/ChangePassword"://修改密码
                        ChangePassword(readParse, response);
                        break;
                    case "/api/QrySqlStr"://查数据
                        Api_QrySqlStr(readParse, response);
                        break;

                    case "/QrySqlStr":
                        QrySqlStr(readParse, response);
                        break;
                    default:
                        {
                            response.WriteFailure();
                        }
                        break;
                }
            }
        }

        private void ChangePassword(HttpReadParse readParse, HttpResponse response)
        {
            WebRsp webrsp = new WebRsp();
            string token = "";
            string oldpassword = "";
            string newpassword = "";
            foreach (var item in readParse.GetBodyParamBuffer())
            {
                if (Encoding.UTF8.GetString(item.Key) == "oldpassword")
                {
                    oldpassword = Encoding.UTF8.GetString(item.Value);
                }
                if (Encoding.UTF8.GetString(item.Key) == "newpassword")
                {
                    newpassword = Encoding.UTF8.GetString(item.Value);
                }
                if (Encoding.UTF8.GetString(item.Key) == "token")
                {
                    token = Encoding.UTF8.GetString(item.Value);
                }
            }
            if (Program.tokenUserDic.ContainsKey(token))
            {
                var user = Program.tokenUserDic[token];
                if (user != null)
                {
                    if (!string.IsNullOrEmpty(oldpassword) || !string.IsNullOrEmpty(newpassword))
                    {
                        if (user.Password == oldpassword)
                        {
                            user.Password = newpassword;
                            Program.UpdateSetting("users", JsonConvert.SerializeObject(Program.users));
                            webrsp.code = 0;
                            webrsp.errmsg = "密码修改成功";
                        }
                        else
                        {
                            webrsp.code = -1;
                            webrsp.errmsg = "密码验证错误";
                        }
                    }
                    else
                    {
                        webrsp.code = -1;
                        webrsp.errmsg = "密码不能为空";
                    }

                }
                else
                {
                    webrsp.code = -1;
                    webrsp.errmsg = "用户未登录";
                }
            }
            else
            {
                webrsp.code = -1;
                webrsp.errmsg = "用户未登录";
            }
            response.WriteSuccess();
            response.Write(JsonConvert.SerializeObject(webrsp));
        }

        private void Api_QrySqlStr(HttpReadParse readParse, HttpResponse response)
        {
            WebRsp webrsp = new WebRsp();
            string value = "";
            foreach (var item in readParse.GetReqParam())
            {
                if (item.Key == "value")
                {
                    value = item.Value;
                }
            }
            string sql = AESHelp.Decrypt(Convert.FromBase64String(value), Convert.FromBase64String(HundSunDB.key), Convert.FromBase64String(HundSunDB.iv));
            foreach (var item in readParse.GetBodyParamBuffer())
            {
                if (Encoding.UTF8.GetString(item.Key) == "sql")
                {
                    sql = Encoding.UTF8.GetString(item.Value);
                }
            }
            if (sql != "")
            {
                // 设置Oracle数据库连接字符串
                string connectionString = "User Id=hs_user;Password=hundsun;Data Source=//10.16.76.70:1521/nuf20bk;";
                // 创建Oracle连接对象
                using (OracleConnection connection = new OracleConnection(connectionString))
                {
                    try
                    {
                        // 打开数据库连接
                        connection.Open();
                        OracleCommand command = connection.CreateCommand();
                        command.CommandText = sql;
                        var records = SqlHelp.getRecords(command);
                        foreach (var r in records)
                        {
                            Dictionary<string, string> data = new Dictionary<string, string>();
                            foreach (var item in r)
                            {
                                data.Add(item.Key, item.Value.ToString());
                            }
                            webrsp.data.Add(data);
                        }
                        webrsp.code = 0;
                        webrsp.errmsg = "正常";
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error connecting to Oracle database: " + ex.StackTrace);
                        webrsp.code = -1;
                        webrsp.errmsg = ex.Message;
                    }
                }
            }
            else
            {
                webrsp.code = -1;
                webrsp.errmsg = "sql为空";
            }
            response.WriteSuccess();
            response.Write(JsonConvert.SerializeObject(webrsp));
        }

        private void UserLogin(HttpReadParse readParse, HttpResponse response)
        {
            WebRsp webrsp=new WebRsp();
            List<Dictionary<string, string>> rsp = new List<Dictionary<string, string>>();
            string UserID = "";
            string Password = "";
            foreach (var item in readParse.GetBodyParamBuffer())
            {
                if (Encoding.UTF8.GetString(item.Key) == "UserID")
                {
                    UserID = Encoding.UTF8.GetString(item.Value);
                }
                else if (Encoding.UTF8.GetString(item.Key) == "Password")
                {
                    Password = Encoding.UTF8.GetString(item.Value);
                }
            }
            if (string.IsNullOrEmpty(UserID) || string.IsNullOrEmpty(Password))
            {
                webrsp.code = -1;
                webrsp.errmsg = "用户名或密码为空";
            }
            else
            {
                User thisuser = null;
                foreach (var user in Program.users)
                {
                    if (user.UserID==UserID&&user.Password==Password)
                    {
                        thisuser = user;
                        break;
                    }
                }
                if (thisuser == null)
                {
                    webrsp.code = -1;
                    webrsp.errmsg = "用户名或密码错误";
                }
                else
                {
                    webrsp.code = 0;
                    webrsp.errmsg = "成功";
                    string token = CalculateToken($"{UserID}|{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                    Program.tokenUserDic.Add(token, thisuser);
                    webrsp.data.Add(token);
                }
            }
            response.WriteSuccess();
            response.Write(JsonConvert.SerializeObject(webrsp));
        }
        static string CalculateToken(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                // 将输入字符串转换为字节数组
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);

                // 计算MD5哈希值
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // 将字节数组转换为字符串表示形式
                StringBuilder sb = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    sb.Append(b.ToString("x2"));
                }

                return sb.ToString();
            }
        }

        public void QrySqlStr(HttpReadParse readParse, HttpResponse response) 
        {
            List<Dictionary<string, string>> rsp = new List<Dictionary<string, string>>();
            string sql = "";
            foreach (var item in readParse.GetReqParam())
            {
                if (item.Key=="sql")
                {
                    sql = item.Value;
                }
            }
            foreach (var item in readParse.GetBodyParamBuffer())
            {
                if (Encoding.UTF8.GetString(item.Key) == "sql")
                {
                    sql = Encoding.UTF8.GetString(item.Value);
                }
            }
            if (sql!="")
            {
                // 设置Oracle数据库连接字符串
                string connectionString = "User Id=hs_user;Password=hundsun;Data Source=//10.16.76.70:1521/nuf20bk;";
                // 创建Oracle连接对象
                using (OracleConnection connection = new OracleConnection(connectionString))
                {
                    try
                    {
                        // 打开数据库连接
                        connection.Open();
                        OracleCommand command = connection.CreateCommand();
                        command.CommandText = sql;
                        var records = SqlHelp.getRecords(command);
                        foreach (var r in records)
                        {
                            try
                            {
                                Dictionary<string, string> data=new Dictionary<string, string>();
                                foreach (var item in r)
                                {
                                    data.Add(item.Key,item.Value.ToString());
                                }
                                rsp.Add(data);
                            }
                            catch (Exception)
                            {
                                Console.WriteLine(JsonConvert.SerializeObject(r));
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error connecting to Oracle database: " + ex.StackTrace);
                    }
                }
            }
            response.WriteSuccess();
            response.Write(JsonConvert.SerializeObject(rsp));
        }

        public override void WsConnected(SocketAsyncEventArgs e)
        {
            //throw new NotImplementedException();
        }

        public override void WsDataOn(byte[] data, SocketAsyncEventArgs e)
        {
            //throw new NotImplementedException();
        }

        public override void WsDisConnected(SocketAsyncEventArgs e)
        {
            //throw new NotImplementedException();
        }
    }
}
